//
//  MyCell.swift
//  demo01
//
//  Created by babybus on 2025/6/24.
//
import Foundation
import UIKit

class MyCell: UICollectionViewCell {
    
    // MARK: - 子视图
    private let imageView: UIImageView = {
        let iv = UIImageView()
        iv.clipsToBounds = true
        iv.layer.cornerRadius = 8
        iv.setContentHuggingPriority(.defaultHigh, for: .horizontal) // 防止图片被过度拉伸
        return iv
    }()
    
    public let titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        label.textAlignment = .left
        label.numberOfLines = 0
        label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) // 允许文字压缩
        return label
    }()
    private let containerStack: UIStackView = {
         let stack = UIStackView()
         stack.axis = .horizontal
         stack.alignment = .center    // 垂直居中
         stack.distribution = .fill
         stack.spacing = 8
         return stack
     }()
    private let cellButton:UIButton={
        let button = UIButton();
        button.setImage(UIImage(systemName: "chevron.right"),for:.normal);
        button.tintColor = .gray;
        button.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        return button;
    }()
    public var targetView: UIViewController.Type?;
    //=================================================
    //=================================================
    //弱引用委托
    weak var delegateTest:MyCellButtonDelegate?

    //委托协议
    protocol MyCellButtonDelegate:AnyObject {
        func didTapButton(in cell:MyCell);
        func didTapButtonTest(in cell:MyCell);
    }
    //按钮点击
    @objc private func goToNextView(){
        delegateTest?.didTapButton(in: self);
    }
    //=================================================
    //=================================================
    
    
    // MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)

        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 配置方法
    func configure(with image: UIImage?, title: String,targetType:UIViewController.Type) {
        imageView.image = image
        titleLabel.text = title
        targetView = targetType;
        
        
        // 根据图片设置宽高比约束
        if let image = image {
            let aspectRatio = image.size.width / image.size.height
            imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor, multiplier: aspectRatio).isActive = true
        }
    }
    
    
    // MARK: - 布局
    private func setupUI() {
        
        let tempStack = UIStackView();
        tempStack.axis = .horizontal;
        tempStack.alignment = .center;
        tempStack.distribution = .fill;
        tempStack.spacing = 8;
        
        // 添加子视图
        tempStack.addArrangedSubview(imageView);
        tempStack.addArrangedSubview(titleLabel);
        containerStack.addArrangedSubview(tempStack);
        containerStack.addArrangedSubview(cellButton);
        contentView.addSubview(containerStack);
        containerStack.translatesAutoresizingMaskIntoConstraints = false;
        
        
        // 设置约束（图片在上，文字在下）
        NSLayoutConstraint.activate([
            containerStack.topAnchor.constraint(equalTo: contentView.topAnchor,constant: 8),
            containerStack.leadingAnchor.constraint(equalTo: contentView.leadingAnchor,constant: 8),
            containerStack.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8),
            containerStack.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8),
            
            imageView.heightAnchor.constraint(lessThanOrEqualToConstant:64),
            imageView.widthAnchor.constraint(greaterThanOrEqualToConstant: 30)
        ])
        
        cellButton.addTarget(self, action: #selector(goToNextView), for: .touchUpInside)
    }
    
    // MARK: - 重用准备
    override func prepareForReuse() {
        super.prepareForReuse()
        imageView.image = nil
        titleLabel.text = nil
        cellButton.removeTarget(nil, action: nil, for: .allEvents)
    }
    var currentImage:UIImage?{
        return imageView.image;
    }
}
